package router

import (
	"github.com/gin-gonic/gin"
	jwt "github.com/golangblogs/gojwt"
	"study-plan/api/client"
	"study-plan/api/request"
	"study-plan/api/response"
	"study-plan/common/proto/study"
)

func UserRegister(c *gin.Context) {
	var data request.UserRegisterRequest
	if err := c.ShouldBind(&data); err != nil {
		response.ResponseError(c, "错误", err)
		return
	}
	res, err := client.UserRegister(c, &study.UserRegisterRequest{
		UserName:    data.UserName,
		Password:    data.Password,
		NewPassword: data.NewPassword,
	})
	if err != nil {
		response.ResponseError(c, err.Error(), nil)
		return
	}
	response.ResponseSuccess(c, "注册成功", res.UserId)
}
func UserLogin(c *gin.Context) {
	var data request.UserLoginRequest
	if err := c.ShouldBind(&data); err != nil {
		response.ResponseError(c, "错误", err)
		return
	}
	res, err := client.UserLogin(c, &study.UserLoginRequest{
		UserName: data.UserName,
		Password: data.Password,
	})
	if err != nil {
		response.ResponseError(c, err.Error(), nil)
		return
	}
	claims := jwt.CustomClaims{ID: uint(res.UserId)}
	token, err := jwt.NewJWT("qq").CreateToken(claims)
	if err != nil {
		response.ResponseError(c, "jwt加密失败", nil)
		return
	}
	response.ResponseSuccess(c, "登录成功", token)
}
func CarList(c *gin.Context) {
	userId := c.GetUint("userId")
	res, err := client.CarList(c, &study.CarListRequest{
		UserId: int64(userId),
	})
	if err != nil {
		response.ResponseError(c, err.Error(), nil)
		return
	}
	response.ResponseSuccess(c, "购物车查看", res.List)
}
func CarCreate(c *gin.Context) {
	userId := c.GetUint("userId")
	var data request.CarCreateRequest
	if err := c.ShouldBind(&data); err != nil {
		response.ResponseError(c, "错误", err)
		return
	}
	res, err := client.CarCreate(c, &study.CarCreateRequest{
		UserId:   int64(userId),
		CourseId: data.CourseId,
	})
	if err != nil {
		response.ResponseError(c, err.Error(), nil)
		return
	}
	response.ResponseSuccess(c, "购物车添加", res.CourseId)
}
func CarDelCourse(c *gin.Context) {
	userId := c.GetUint("userId")
	var data request.CarDelCourseRequest
	if err := c.ShouldBind(&data); err != nil {
		response.ResponseError(c, "错误", err)
		return
	}
	res, err := client.CarDelCourse(c, &study.CarDelCourseRequest{
		UserId:   int64(userId),
		CourseId: data.CourseId,
	})
	if err != nil {
		response.ResponseError(c, err.Error(), nil)
		return
	}
	response.ResponseSuccess(c, "购物车移除", res.Success)
}
func OrderCreate(c *gin.Context) {
	userId := c.GetUint("userId")
	var data request.OrderCreateRequest
	if err := c.ShouldBind(&data); err != nil {
		response.ResponseError(c, "错误", err)
		return
	}
	res, err := client.OrderCreate(c, &study.OrderCreateRequest{
		UserId:   int64(userId),
		CourseId: data.CourseId,
	})
	if err != nil {
		response.ResponseError(c, err.Error(), nil)
		return
	}
	response.ResponseSuccess(c, "订单创建成功", map[string]interface{}{
		"Id":  res.OrderId,
		"Url": res.Url,
	})
}
